﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;

namespace AppRunner
{
    class Program
    {

        static readonly List<Process> Processes=new List<Process>(2); 

        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

            string exeFile = ConfigurationManager.AppSettings["brunchExePath"];
            string arguments = "w -s";


            string startAt = string.Format("{0}\\{1}",
                                           Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigurationManager.AppSettings["appToRunRelativePath"]);
            Processes.Add(StartProccess(exeFile, arguments, startAt, true));
            Thread.Sleep(TimeSpan.FromSeconds(3));

            exeFile = ConfigurationManager.AppSettings["firefoxExePath"];
            arguments = "localhost:3333";

            Processes.Add(StartProccess(exeFile, arguments));
            Processes.AddRange(Process.GetProcesses().Where(x => x.ProcessName == "node"));
            Console.WriteLine("Press key to finish...");
            Console.ReadKey();


        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            foreach(var process in Processes)
            {
                try{process.Kill();}catch{}
            }
        }


        private static Process StartProccess(string exeFile, string arguments,string startAt=null,bool redirectOutput=false)
        {
            var process = new Process
                              {
                                  StartInfo =
                                      {
                                          FileName = exeFile, 
                                          Arguments = arguments,
                                          UseShellExecute = false,    
                                          RedirectStandardOutput = redirectOutput
                                      }
                              };
            if (!string.IsNullOrEmpty(startAt))
                process.StartInfo.WorkingDirectory = startAt;
            process.Start();
            return process;
        }
    }
}
